package cn.edu.pzhu.javaweb.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;

import cn.edu.pzhu.javaweb.pojo.Result;
import cn.edu.pzhu.javaweb.pojo.Userinfo;
import cn.edu.pzhu.javaweb.service.UserService;
import cn.edu.pzhu.javaweb.service.imp.UserServiceImp;

/**
 * Servlet implementation class UpdateUserInfoServlet
 */
@WebServlet("/updateuserinfo")
public class UpdateUserInfoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserService userService = new UserServiceImp();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateUserInfoServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

    	String username = (String) request.getSession().getAttribute("username");
        String email = request.getParameter("email");// 接收邮箱
        String sex = request.getParameter("sex");// 接收性别
        String[] types = request.getParameterValues("type"); // 接收关注类型
        if (username == null || username.isEmpty() || email == null || email.isEmpty()) {
            response.getWriter().print("<script>alert('信息不完整!');location.href='userinfo';</script>");
            return;
        }
        if (sex == null || sex.equals("")) {
            sex = "1";
        }

        Userinfo userinfo = new Userinfo(username, email, Integer.valueOf(sex), JSON.toJSONString(types));
        Result<String> result = userService.UpdatePersonalInfo(userinfo);
        if (result.getCode() == 0) {
            response.getWriter().print("<script>alert('修改成功');location.href='userinfo';</script>");
        } else {
            response.getWriter().print("<script>alert('" + result.getMessage() + "');location.href='userinfo';</script>");
        }
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
